<template>
  <!-- 赛事天气 十日天气 赛装建议 装备推荐 -->
  <div class="pageWrap">
    <span class="oTxt">开启赛事天气</span>
    <el-switch
      v-model="openweather"
      active-color="#13ce66"
      inactive-color="#ff4949"
      :active-value="1"
      :inactive-value="0"
      :disabled="!canOpen"
      @change="weatherChange"
    ></el-switch>
    <p class="tip">注：赛事天气开启需完善赛事站点集合经纬度坐标信息，请确认已完善</p>
    <el-form class="el_from" v-show="openweather==1">
      <el-form-item label="十日天气" class="block">
        <el-select v-model="seePointWea" placeholder="请选择" @change="getWeather">
          <el-option
            v-for="item in matchPoints"
            :key="item.id"
            :label="item.cpName"
            :value="item.id"
          ></el-option>
        </el-select>
        <div class="ech" ref="myCharts"></div>
      </el-form-item>
      <el-form-item label="装备推荐：">
        <el-button type="primary" @click="addRecommend">添加</el-button>
        <el-table :data="recommendArr" style="width: 100%">
          <el-table-column prop="uid" label="商品编号" width="180"></el-table-column>
          <el-table-column label="商品图片" width="150">
            <template slot-scope="{row}">
              <img :src="row.imgUrl" class="recomImg" />
            </template>
          </el-table-column>
          <el-table-column prop="address" label="商品名称">
            <template slot-scope="{row}">
              <el-select v-model="row.id" placeholder="请选择" filterable @change="recomChange(row)">
                <el-option
                  v-for="item in goodsArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="原价"></el-table-column>
          <el-table-column prop="tmPrice" label="活动价"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{$index}">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                v-if="$index!=0"
                @click="recommendArr.splice($index,1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveData()">保存推荐</el-button>
        <el-button type="warning" @click="resetData()">清空重置</el-button>
      </el-form-item>
      <el-tabs type="card" v-model="activeGroupI" @tab-click="groupChange">
        <el-tab-pane v-for="(v,i) in groupArr" :key="i" :label="v.name" :name="'g'+i"></el-tab-pane>
      </el-tabs>
      <el-form-item label="赛装建议：">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6}"
          placeholder="请输入内容"
          v-model="suggest"
        ></el-input>
      </el-form-item>
      <el-button type="primary" @click="saveSuggest()">保存建议</el-button>
    </el-form>
  </div>
</template>

<script>
// import echarts from "echarts";
import echarts from "echarts";
var matchDS = "",
  matchDE = "";
var recommend = { id: "", uid: "", imgUrl: "", price: "", tmPrice: "" };
export default {
  data() {
    return {
      activeGroupI: "g0",
      groupArr: [],
      openweather: 0,
      canOpen: false,
      matchPoints: [],
      seePointWea: "",
      recommendArr: [],
      goodsArr: [], //商品列表
      suggest: "", // 赛装建议
    };
  },
  methods: {
    // 获取赛项
    getGroupArr() {
      this.$axios
        .get("/sbr/match/getMatchInfos/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          matchDS = rr.matchDate;
          matchDE = rr.matchEndDate;
          this.groupArr = rr.matchInfoLists;
          this.groupChange();
          if (this.openweather == 1) {
            this.getWeather();
          }
        });
    },
    // 切换赛项
    groupChange() {
      let ii = this.activeGroupI.replace(/g/g, "");
      this.suggest = this.groupArr[ii].suggest;
    },
    // 获取天气开启状态
    getWeatherState() {
      this.$axios
        .get("/sbr/match/getMatchIfWeather/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          this.openweather = rr;
          if (rr == 1) this.getGoodsArr();
        });
    },
    // 修改赛事天气开启状态
    weatherChange() {
      this.$axios
        .get("/sbr/match/editmatchIfWeather/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          if (this.openweather == 1) {
            this.getWeather();
            this.getGoodsArr();
          }
        });
    },
    // 十日天气echarts
    forEch(max, min, data, state, dateArea) {
      const myCharts = echarts.init(this.$refs.myCharts);
      let options = {
        title: {
          text: "", //图表顶部的标题
          subtext: "", //副标题
        },
        tooltip: {
          //鼠标悬浮框的提示文字
          trigger: "axis",
          formatter: function (params) {
            var htmlStr = "";
            for (var i = 0; i < params.length; i++) {
              var param = params[i];
              var xName = param.name; //x轴的名称
              var seriesName = param.seriesName; //图例名称
              var value = param.value; //y轴值
              var color = param.color; //图例颜色

              if (i === 0) {
                htmlStr += xName + "<br/>"; //x轴的名称
              }
              htmlStr += "<div>";

              // 具体显示的数据【字段名称：seriesName，值：value】
              // 这里判断一下name，如果是我们需要特殊处理的，就处理
              if (seriesName === "天气状态") {
                // 前面一条线，后面一条线【具体样式自己写】
                htmlStr += "天气状态：" + value;
              } else {
                // 正常显示的数据，走默认
                // htmlStr +=
                //   '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' +
                //   color +
                //   ';"></span>';
                htmlStr += seriesName + "：" + value + "℃";
              }

              htmlStr += "</div>";
            }
            return htmlStr;
          },
        },
        legend: {
          data: ["最高气温", "最低气温"],
        },
        xAxis: [
          {
            //x轴坐标数据
            type: "category",
            data: data,
            axisLabel: {
              show: true,
              textStyle: {
                color: function (value) {
                  let i = dateArea.findIndex((v) => {
                    return v == value;
                  });
                  if (i >= 0) return "red";
                  else return "#333";
                },
              },
              formatter: (val, ind) => {
                let v = val + "\n" + state[ind];
                return v;
              },
            },
          },
        ],
        yAxis: [
          {
            //y轴坐标数据
            type: "value",
            axisLabel: {
              formatter: "{value} °C",
            },
          },
        ],
        series: [
          //驱动图表生成的数据内容数组，几条折现，数组中就会有几个对应对象，来表示对应的折线
          {
            name: "最高气温",
            type: "line", //pie->饼状图  line->折线图  bar->柱状图
            data: max,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                },
              },
            },
          },
          {
            name: "最低气温",
            type: "line", //pie->饼状图  line->折线图  bar->柱状图
            data: min,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                },
              },
            },
          },
          {
            name: "天气状态",
            type: "line", //pie->饼状图  line->折线图  bar->柱状图
            data: state,
          },
        ],
      };

      myCharts.setOption(options);
    },
    // 获取十日天气数据
    getWeather() {
      let latlng = this.matchPoints.find((v) => {
        return v.id == this.seePointWea;
      });
      let an = { lat: latlng.lat, lng: latlng.lng, id: "e" };
      this.$axios.get("/sbr/getWeather", { params: an }).then((res) => {
        let rr = res.data.data.weather;
        let max = rr.map((v) => {
          return v.maxTemperature;
        });
        let min = rr.map((v) => {
          return v.minTemperature;
        });
        let state = rr.map((v) => {
          return v.weather;
        });
        let dateArea = [];
        let d1 = matchDS.substring(0, 10).replace(/-/g, "");
        let d2 = matchDE.substring(0, 10).replace(/-/g, "");
        let md = [d1, d2];
        let data = rr.map((v) => {
          let vv = v.bjTime.substring(4, 6) + "-" + v.bjTime.substring(6, 8);
          if (md.length > 0 && v.bjTime >= md[0] && v.bjTime <= md[1])
            dateArea.push(vv);
          return vv;
        });
        // console.log(dateArea)
        this.forEch(max, min, data, state, dateArea);
      });
    },
    // 获取赛事站点 判断是否符合开启条件
    getMatchPoints() {
      this.$axios
        .get("/sbr/match/getMatchCpList/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          if (
            rr.find((v) => {
              return v.lat == 0 || v.lng == 0;
            })
          ) {
            this.canOpen = false;
          } else {
            this.canOpen = true;
          }
          this.matchPoints = rr;
          this.seePointWea = rr[0].id;
          this.getWeatherState();
          this.getGroupArr();
        });
    },
    // 获取商品列表
    getGoodsArr() {
      this.$axios.get("/sbr/shop/getShopKu?name=&brand=&type=").then((res) => {
        let rr = res.data.data;
        this.goodsArr = rr;
      });
    },
    // 添加推荐装备
    addRecommend() {
      this.recommendArr.push(JSON.parse(JSON.stringify(recommend)));
    },
    // 选择推荐装备
    recomChange(row) {
      console.log(row.id);
      let val = this.goodsArr.find((v) => {
        return v.id == row.id;
      });
      if (val) {
        Object.assign(row, val);
      }
    },
    // 保存 推荐
    saveData() {
      let goodsIds = this.recommendArr.filter((v) => {
        return v.id != "";
      });
      if (goodsIds.length == 0) {
        this.$$message.error("请选择推荐装备");
        return false;
      }
      goodsIds = goodsIds
        .map((v) => {
          if (v.id != "") return v.id;
        })
        .join(",");
      let oo = {
        matchId: Number(this.$Base64.decode(sessionStorage.getItem("MandA"))),
        ids: goodsIds,
      };
      this.$axios.post("/sbr/shop/addShop", oo).then((res) => {
        this.getRecommend();
        this.$message.success("装备推荐保存成功");
      });
    },
    // 重置推荐
    resetData() {
      let oo = {
        matchId: Number(this.$Base64.decode(sessionStorage.getItem("MandA"))),
        ids: "",
      };
      this.$axios.post("/sbr/shop/addShop", oo).then((res) => {
        this.getRecommend();
        this.$message.success("装备推荐重置成功");
      });
    },
    // 建议保存
    saveSuggest() {
      let ii = this.activeGroupI.replace(/g/g, "");
      let gId = this.groupArr[ii].id;
      let oo = { id: gId, suggest: this.suggest };
      console.log(oo);
      this.$axios.post("/sbr/match/putMatchInfoSuggest", oo).then((res) => {
        this.groupArr[ii].suggest = this.suggest;
      });
    },
    // 获取推荐装备
    getRecommend() {
      this.$axios
        .get("/sbr/shop/getShopByMatchId/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          if (!rr||rr.length == 0) rr = [JSON.parse(JSON.stringify(recommend))];
          this.recommendArr = rr;
        });
    },
  },
  mounted() {
    // this.getWeather(25.44292, 106.75857);
    this.getMatchPoints();
    this.getRecommend();
  },
};
</script>
<style scoped>
/* @import url(); 引入公共css类 */
.oTxt {
  float: left;
  margin-right: 8px;
}
.tip {
  margin-top: 10px;
}
.el_from {
  margin-top: 10px;
  overflow: hidden;
}

.ech {
  width: 100%;
  height: 300px;
}
.recomImg {
  width: 100px;
}
</style>